from django.conf import settings
from rest_framework import serializers
from django_redis import get_redis_connection
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from rest_framework_jwt.settings import api_settings
from users.models import User
from oauth.models import OAuthQQModel



class OAuthQQSerializer(serializers.Serializer):
    mobile = serializers.RegexField(regex="1[3-9]\d{9}",max_length=16)
    password = serializers.CharField(max_length=20,min_length=8,write_only=True)
    sms_code=serializers.CharField(max_length=6,min_length=6,write_only=True)
    access_token = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True)
    username = serializers.CharField(read_only=True)

    def validate(self, attrs):
        # 短信验证码验证
        # 从缓存中取出短信
        conn = get_redis_connection('verify')
        sms_code_real = conn.get('sms_code_%s' % attrs['mobile'])
        # 获取不到短信
        if not sms_code_real:
            raise serializers.ValidationError('短信失效')

        if attrs['sms_code'] != sms_code_real.decode():
            raise serializers.ValidationError('短信不一致')


        openid = OAuthQQModel.decode_token(attrs['access_token'])
        # 添加openeid到attrs
        attrs['openid'] = openid

        # 用户验证
        # 1、用户查询不到
        try:
            user = User.objects.get(mobile=attrs['mobile'])
        except:
            return attrs  # 没有user对象

        # 用户查询到  校验密码
        if user.check_password(attrs['password']):
            # 添加user到attrs
            attrs['user'] = user

        return attrs

    def create(self, validated_data):
        # 绑定操作  创建出OAuthQQModel模型类对象
        print(validated_data)
        # 用户查询
        user = validated_data.get('user', None)

        if not user:
            # user是none值说明用不存在
            # 创建新用户
            user = User.objects.create_user(username=validated_data['mobile'], password=validated_data['password'],
                                            mobile=validated_data['mobile'])

        # 绑定user和openid
        OAuthQQModel.objects.create(user=user, openid=validated_data['openid'])

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user
